//
//  AppDelegate.m
//  EasyMoney
//
//  Created by zh on 2019/12/12.
//  Copyright © 2019 zh. All rights reserved.
//

#import "AppDelegate.h"
#import "ICEH5Bridge.h"
#import <AFNetworkReachabilityManager.h>
#import "EMAgreementViewController.h"
#import <JPUSHService.h>
#import <Bugly/Bugly.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

static NSString* jpush_release_appKey = @"8a4c9ffdb7b659e0168b067a";
static NSString* jpush_debug_appKey = @"8a4c9ffdb7b659e0168b067a";

@interface AppDelegate () <JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (EMNavigationController *)mainModule
{
    if (!_mainModule) {
        EMTabBarController* tab = [[EMTabBarController alloc] init];
        _mainModule = [[EMNavigationController alloc] initWithRootViewController:tab];
    }
    return _mainModule;
}

//可以使用一下语句判断是否是刘海手机：
+ (BOOL)isPhoneX {
    BOOL iPhoneX = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判断是否是手机
       return iPhoneX;
    }
    if (@available(iOS 11.0, *)) {
       UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
       if (mainWindow.safeAreaInsets.bottom > 0.0) {
           iPhoneX = YES;
       }
    }
    return iPhoneX;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    if ([EMAgreementViewController needShowAgreement]) {
        EMAgreementViewController *agree = [[EMAgreementViewController alloc] init];
        [self.mainModule emPresentViewController:agree animated:NO];
    }
    
    self.window.rootViewController = self.mainModule;
    [self.window makeKeyAndVisible];

    [self registerThirdPartWithOptions:launchOptions];
    
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    NSDictionary* privateMap = @{
                                   @"home":@"EMTabBarController",
                                   @"login":@"EMLoginViewController",
                                   @"web":@"EMWebViewController",
                                   @"tel":@"EMTelObject"
                                   };
    NSDictionary* publicMap = @{
                                   @"home":@"EMTabBarController",
                                   @"login":@"EMLoginViewController",
                                   @"web":@"EMWebViewController",
                                   @"tel":@"EMTelObject"
                                   };
    
    [ICENavigator loadWithRootNavigationController:self.mainModule schemeArray:@[@"emoney"] privateUrlMappingDictionary:privateMap publicUrlMappingDictionary:publicMap];
    [ICENavigator setTopLevelViewControllers:@[] exceptionViewControllers:@[@"EMLoginViewController"]];
    
    return YES;
}

- (void)registerThirdPartWithOptions:(NSDictionary *)launchOptions
{
    [Bugly startWithAppId:@"a497e6c0a8"];
    NSString *userId = UserInfoShared.userId;
    if (userId.length > 0) {
        [Bugly setUserIdentifier:userId];
    }
    
    [self registerJPushWithLaunchOptions:launchOptions];
    
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    if ([ICENavigator canOpenOutSideWithUrlScheme:[url absoluteString]]) {
        [ICENavigator openURLString:[url absoluteString] fromViewController:nil];
    }
    return YES;
}

- (void)handleRemoteMessage:(NSDictionary *)message
{
    if ([message objectForKey:@"url"])
    {
        ICEOpenUrl(message[@"url"]);
    }
}

- (void)cleanBadge {
    NSInteger badgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber;
    if (badgeNumber > 0) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [JPUSHService setBadge:0];
    }
}

- (void)registerJPushWithLaunchOptions:(NSDictionary *)launchOptions
{
    //推送
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    NSInteger entityType = 0;
    if (@available(iOS 12.0, *)) {
        entityType = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entityType = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    entity.types = entityType;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    NSString *JPushAppKey = nil;
    BOOL apsForProduction = NO;
#if defined(DEBUG)
    JPushAppKey = jpush_debug_appKey;
    apsForProduction = NO;
#else
    JPushAppKey = jpush_release_appKey;
    apsForProduction = YES;
#endif
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:@"AppStore" apsForProduction:apsForProduction];
    [self cleanBadge];
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification) {
        [self handleRemoteMessage:remoteNotification];
    }
}

#pragma mark- Push
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSString *deviceTokenString = nil;
    if ([deviceToken isKindOfClass:[NSData class]])
    {
        const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
        deviceTokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                              ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                              ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                              ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    }

//    __weak typeof(self)weakSelf = self;
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
//        [weakSelf uploadDeviceToken:deviceTokenString registerId:registrationID];
    }];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteMessage:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
    [self handleRemoteMessage:userInfo];
}

#pragma mark- JPUSHRegisterDelegate

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler  API_AVAILABLE(ios(10.0)){//前台
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self handleRemoteMessage:userInfo];
    } else {
        // 本地通知
    }

    NSInteger options = UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound;
    completionHandler(options); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler  API_AVAILABLE(ios(10.0)){//后台
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [self handleRemoteMessage:userInfo];
    } else {
        //本地通知
    }
    completionHandler();  // 系统要求执行这个方法
}

/*
 * @brief handle UserNotifications.framework [openSettingsForNotification:]
 * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心
 * @param notification 当前管理的通知对象
 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification NS_AVAILABLE_IOS(12.0){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}

/**
 * 监测通知授权状态返回的结果
 * @param status 授权通知状态，详见JPAuthorizationStatus
 * @param info 更多信息，预留参数
 */
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info
{
    
}

@end
